import Basemap from '@/assets/api/basemap'
import esriLoader from 'esri-loader'
import centerstarPng from '@/assets/mapimg/centerstar.png'
import centerstarTwoPng from '@/assets/mapimg/centerStarTwo.png'
import nearCityPng from '@/assets/mapimg/nearCity.png'
import nearCityPngThree from '@/assets/mapimg/nearCity3.png'
import checkedPng from '@/assets/mapimg/checked.png'
import nocheckedPng from '@/assets/mapimg/nochecked.png'
import HIS_EQ_MARKER_1 from '@/assets/imgicon/tdhis1.png'
import HIS_EQ_MARKER_2 from '@/assets/imgicon/tdhis2.png'
import HIS_EQ_MARKER_3 from '@/assets/imgicon/tdhis3.png'
import Other_EQ_MARKER from '@/assets/imgicon/tdhisother.png'
function ArcMap(id, eqCenter) {
    this.HIS_EQ_MARKER = [HIS_EQ_MARKER_1, HIS_EQ_MARKER_2, HIS_EQ_MARKER_3];
    this.eqCenter = eqCenter;
    //this.mapData = mapData;
    this.hisEq = null;
    this.gDistanceLine = [];
    this.gmapMarkers = [];
    this.map = null;
    this.view = null;
    this.obj = null;
    this.GraphicsLayer = null;
    this.activeWidget = null
    //js来源
    let option = {
        url: "http://47.92.216.173/arcgis/init.js"
    }
    //加载css
    esriLoader.loadCss('http://47.92.216.173/arcgis/esri/css/main.css');

    esriLoader.loadModules([
        "arcgis/esri/Map",
        "arcgis/esri/Basemap",
        "arcgis/esri/views/SceneView",
        "arcgis/esri/layers/ElevationLayer",
        "arcgis/esri/layers/BaseElevationLayer",
        "arcgis/esri/layers/WebTileLayer",
        "arcgis/esri/layers/support/TileInfo",
        "arcgis/esri/layers/OpenStreetMapLayer",
        "arcgis/esri/widgets/Home",
        "arcgis/esri/widgets/Fullscreen",
        "arcgis/esri/config",
        "arcgis/esri/widgets/DirectLineMeasurement3D",
        "arcgis/esri/widgets/Legend",
        "arcgis/esri/widgets/Expand",
        "arcgis/dojo/domReady!",
    ],option).then(([Map, Basemap, SceneView, ElevationLayer, BaseElevationLayer, WebTiledLayer, TileInfo, OpenStreetMapLayer, Home, Fullscreen, esriConfig, DirectLineMeasurement3D, Legend, Expand, featureLayer, BasemapGallery, domReady]) => {
        var ExaggeratedElevationLayer = BaseElevationLayer.createSubclass({
            //高程夸张系数
            properties: {
                exaggeration: 1
            },
            //加载高程数据
            load: function () {
                this._elevation = new ElevationLayer({
                    url: "//elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"
                });
                this.addResolvingPromise(this._elevation.load());
            },

            //瓦片
            fetchTile: function (level, row, col) {
                return this._elevation.fetchTile(level, row, col)
                    .then(function (data) {

                        var exaggeration = this.exaggeration;

                        for (var i = 0; i < data.values.length; i++) {
                            data.values[i] = data.values[i] * exaggeration;
                        }
                        return data;
                    }.bind(this));
            }
        });
        esriConfig.request.corsEnabledServers.push('http://t0.tianditu.com')
        this.map = new Map({
            basemap: "satellite",//myBaseMap,
            ground: {
                layers: [
                    new ExaggeratedElevationLayer()
                ]
            },
            showLabels: true,
            wkid: 4326//所用坐标系
        });

        //view
        this.view = new SceneView({
            container: id,
            viewingMode: "global",
            //viewingMode: "global",
            map: this.map,
            camera: {
                position: {
                    x: eqCenter.lon,
                    y: eqCenter.lat - 0.7,
                    z: 100000,
                },
                heading: 0,
                tilt: 45
            },
            center: [eqCenter.lon, eqCenter.lat],
            constraints: {
                snapToZoom: true
            }
        });
        let homeBtn = new Home({
            view: this.view
        });
        this.view.ui.add(homeBtn, "top-right");
        this.view.popup.collapsed = false
        this.view.popup.dockEnabled = false
        this.view.popup.dockOptions = {
            buttonEnabled: true
        }
        //全屏
        let fullscreen = new Fullscreen({
            view: this.view
        });
        this.view.ui.add(fullscreen, "top-right");

        //量算工具
        this.view.ui.add("topbar", "top-right");

        //三维图例
        let legend = new Expand({
            content: `<div style='background-color:#fff;border-radius:10px;'><h3>图例</h3><p style="width:100px"></p><p><span style='font-size: 16px;'>地震中心:</span><img src=`+centerstarPng+` style='width:16px;height:16px;'></p><p><span style='font-size: 16px;'>附近城镇:</span><img src=`+nearCityPngThree+` style='width:16px;height:16px;'></p><p><span style='font-size: 16px;'>历史地震:</span><img src=`+Other_EQ_MARKER+` style='width:16px;height:16px;'></p></div>`,
            view: this.view,
            // 默认展开折叠
            expanded: false
        });
        this.view.ui.add(legend, "top-right");

        let baseMapMarker = new WebTiledLayer("http://{subDomain}.tianditu.com/dataServer?t=cia_w&x={col}&y={row}&l={level}", {
            copyright: 'Tianditu',
            id: 'Tianditu1',
            subDomains: ['t0'],
        });
        let basedivision = new WebTiledLayer("http://{subDomain}.tianditu.com/dataServer?t=ibo_w&x={col}&y={row}&l={level}", {
            copyright: 'Tianditu',
            id: 'Tianditu2',
            subDomains: ['t0'],
        });
        this.map.add(baseMapMarker);
        this.map.add(basedivision);
    })

}
ArcMap.prototype = new Basemap();
ArcMap.prototype.setMarker = function (data, type) {
    if (type == 'nearCity') {
        esriLoader.loadModules([
            "esri/layers/GraphicsLayer",
            "esri/Graphic",
            "esri/layers/FeatureLayer",
            "dojo/domReady!",
        ]).then(([GraphicsLayer, Graphic, FeatureLayer]) => {

            //var point = new AMap.LngLat(item.longtitude, item.latitude);
            let GLayer = new GraphicsLayer;
            let symbolNear = {
                type: "point-3d",
                symbolLayers: [{
                    type: "icon",  // autocasts as new IconSymbol3DLayer()
                    size: 20,  // points
                    resource: { href: nearCityPngThree },
                    material: { color: "red" }
                }]
            }
            data.forEach(function (item, index) {
                //let lonlat = this.tranMct(item.longtitude,item.latitude)
                let point = {
                    type: 'point',
                    longitude: item.longtitude,//lonlat.x,
                    latitude: item.latitude,//lonlat.y,
                }
                let NearPopupTemplate = {
                    title: "附近城镇信息",
                    content: this.setContent('', item, "nearCity")
                }
                let pointGraphic = new Graphic({
                    geometry: point,
                    symbol: symbolNear,
                    popupTemplate: NearPopupTemplate,
                    overwriteActions: true
                });
                GLayer.labelingInfo = [{
                    labelExpressionInfo: {
                        value: "aaa"
                    },
                    symbol: {
                        type: "label-3d", // autocasts as new LabelSymbol3D()
                        symbolLayers: [{
                            type: "text", // autocasts as new TextSymbol3DLayer()
                            material: {
                                color: "white"
                            },
                            // we set a halo on the font to make the labels more visible with any kind of background
                            halo: {
                                size: 1,
                                color: [50, 50, 50]
                            },
                            size: 10
                        }]
                    }
                }]
                GLayer.add(pointGraphic);

            }.bind(this))

            ///////////////////////////////////////////震中//////////////////////////////////////////////
            let symbolCenter = {
                type: "point-3d",
                symbolLayers: [{
                    type: "icon",  // autocasts as new IconSymbol3DLayer()
                    size: 20,  // points
                    resource: { href: centerstarPng },
                    material: { color: "red" }
                }]
            }

            let pointCenter = {
                type: 'point',
                longitude: this.eqCenter.lon,//lonlat.x,
                latitude: this.eqCenter.lat,//lonlat.y,
            }
            let CenterPopupTemplate = {
                title: "震中信息",
                content: this.setContent('', this.eqCenter, "EqCenter")
            }
            let pointGraphic = new Graphic({
                geometry: pointCenter,
                symbol: symbolCenter,
                popupTemplate: CenterPopupTemplate,
                overwriteActions: true
            });
            GLayer.add(pointGraphic);

            this.map.add(GLayer);
        })
    }
}



ArcMap.prototype.setHisEq = function (hisEq) {
    esriLoader.loadModules([
        "esri/layers/GraphicsLayer",
        "esri/Graphic",
        "dojo/domReady!",
    ]).then(([GraphicsLayer, Graphic]) => {
        let GLayer = new GraphicsLayer
        this.hisEq = hisEq
        for (let key in this.hisEq) {
            let val = this.hisEq[key]
            if (this.HIS_EQ_MARKER[key] == undefined) {
                this.HIS_EQ_MARKER[key] = Other_EQ_MARKER
            }
            let symbolCenter = {
                type: "point-3d",
                symbolLayers: [{
                    type: "icon",  // autocasts as new IconSymbol3DLayer()
                    size: 20,  // points
                    resource: { href: this.HIS_EQ_MARKER[key] },

                }]
            }
            let pointCenter = {
                type: 'point',
                longitude: val.Longitude,//lonlat.x,
                latitude: val.Latitude,//lonlat.y,
            }
            let HisPopupTemplate = {
                title: "历史地震信息",
                content: this.setContent('', val, "hisEq")
            }
            let pointGraphic = new Graphic({
                geometry: pointCenter,
                symbol: symbolCenter,
                popupTemplate: HisPopupTemplate,
                overwriteActions: true
            });
            GLayer.add(pointGraphic);
        }
        this.map.add(GLayer);
    })
}
ArcMap.prototype.tranMct = function (x, y) {

    let mercator = {};
    mercator.x = x * 20037508.34 / 180;
    mercator.y = Math.log(Math.tan((90 + y) * Math.PI / 360)) / (Math.PI / 180);
    y = y * 20037508.34 / 180;
    return mercator;

}
ArcMap.prototype.gotoPan = function (x, y) {
    let option = {
        url: "http://10.5.68.78/arcgisjs/init.js"
    }
    esriLoader.loadModules(["esri/views/SceneView"], option).then(() => {
        this.view.goTo({
            center: [x, y]
        })
    })

}

//添加震中标签
ArcMap.prototype.epiLabel = function () {
    esriLoader.loadModules([
        "esri/layers/FeatureLayer",
        "esri/Graphic"
    ]).then(([FeatureLayer, Graphic]) => {
        let symbolCenter = {
            type: "point-3d",
            symbolLayers: [{
                type: "icon",  // autocasts as new IconSymbol3DLayer()
                size: 20,  // points
                resource: { href: centerstarPng },
                material: { color: "red" }
            }]
        }

        let pointCenter = {
            type: 'point',
            longitude: this.eqCenter.lon,//lonlat.x,
            latitude: this.eqCenter.lat,//lonlat.y,
        }
        let CenterPopupTemplate = {
            title: "震中信息",
            content: this.setContent('', this.eqCenter, "EqCenter"),
            overwriteActions: true
        }
        let pointGraphic = new Graphic({
            geometry: pointCenter,
            symbol: symbolCenter,

        });
        var features = [
            pointGraphic
        ];
        this.peaks = new FeatureLayer({
            //*设置3d标签可见*
            labelsVisible: true,
            source: features,
            popupTemplate: CenterPopupTemplate,
            // Set a renderer that will show the points with icon symbols
            renderer: {
                type: "simple", // autocasts as new SimpleRenderer()
                symbol: {
                    type: "point-3d", // autocasts as new PointSymbol3D()
                    symbolLayers: [{
                        type: "icon", // autocasts as new IconSymbol3DLayer()
                        resource: {
                            primitive: "circle"
                        },
                        material: {
                            color: "yellow"
                        },
                        size: 10
                    }]
                }
            },
            fields: ["*"],
            objectIdField: "ObjectID",
            geometryType: "mulitpoint",
            outFields: ["*"],
            // Add labels with callouts of type line to the icons
            labelingInfo: [{
                // When using callouts on labels, "above-center" is the only allowed position
                //   labelPlacement: "above-center",
                labelExpressionInfo: {
                    value: this.eqCenter.district + this.eqCenter.magn + "级"
                },
                symbol: {
                    type: "label-3d", // autocasts as new LabelSymbol3D()
                    symbolLayers: [{
                        type: "text", // autocasts as new TextSymbol3DLayer()
                        material: {
                            color: "#ff0111"
                        },
                        halo: {
                            color: [0, 0, 0, 0.4],
                            size: 1
                        },
                        size: 20
                    }],
                }
            }]
        });

        this.map.add(this.peaks);
    })
}

//量算分件
ArcMap.prototype.setActiveWidget = function (type) {
    esriLoader.loadModules(["esri/widgets/DirectLineMeasurement3D"]).then(([DirectLineMeasurement3D]) => {
        switch (type) {
            case "distance":
                // debugger
                this.activeWidget = new DirectLineMeasurement3D({
                    view: this.view
                });
                this.view.ui.add(this.activeWidget, "top-right");
                this.setActiveButton(document.getElementById("distanceButton"));
                break;
            case null:
                if (this.activeWidget) {
                    this.view.ui.remove(this.activeWidget);
                    this.activeWidget.destroy();
                    this.activeWidget = null;
                }
                break;
        }
    })

}

//量算分件
ArcMap.prototype.setActiveButton = function (selectedButton) {
    // 将视图聚焦到激活键盘快捷键
    this.view.focus();
    let elements = document.getElementsByClassName("active");
    for (var i = 0; i < elements.length; i++) {
        elements[i].classList.remove("active");
    }
    if (selectedButton) {
        selectedButton.classList.add("active");
    }
}

//量算主件
ArcMap.prototype.measure = function () {
    this.setActiveWidget(null);
    if (!document.getElementById("distanceButton").classList.contains('active')) {
        this.setActiveWidget('distance');
    } else {
        this.setActiveButton(null);
    }
}

//点击任意点弹出窗口
ArcMap.prototype.locator = function () {
    esriLoader.loadModules([
        "esri/tasks/Locator"
    ]).then(([Locator]) => {
        let locatorTask = new Locator({
            url: "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"
        });
        
        this.view.on("click", (event) => {
            // 在视图中获取点击的坐标
            let lat = Math.round(event.mapPoint.latitude * 1000) / 1000;
            let lon = Math.round(event.mapPoint.longitude * 1000) / 1000;
            const screenPoint = {
                x: event.x,
                y: event.y
            };

            //计算两经纬度点之间的距离
            let radLat1 = this.eqCenter.lat * Math.PI / 180.0; //lat纬度
            let radLat2 = lat * Math.PI / 180.0;
            let nearlon = this.eqCenter.lon * Math.PI / 180.0 - lon * Math.PI / 180.0;      //经度
            let nearlat = this.eqCenter.lat * Math.PI / 180.0 - lat * Math.PI / 180.0;      //纬度
            let nearDistance1 = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(nearlat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(nearlon / 2), 2))) * 6378.137;
            let nearDistance = Math.round(nearDistance1 * 10000) / 10000;

            this.view.hitTest(screenPoint).then((response) => {
                if (response.results[0].graphic == null) {
                    console.log(event)
                    event.stopPropagation();
                    this.view.popup.open({
                        // 将弹出的标题设置为位置的坐标
                        title: "此点信息",
                        // 将弹出的位置设置为单击的位置
                        location: event.mapPoint
                    });
                    let z = event.mapPoint.z>=0?event.mapPoint.z:无此处信息;
                    // 显示弹窗
                    // 使用点击的位置执行反向地理代码
                    locatorTask.locationToAddress(event.mapPoint).then((response) => {
                        // 如果成功找到了地址，请在弹出的内容中显示它
                        this.view.popup.content = '<table class="table-bordered table-condensed"><tr><td width="45%">'+"经纬度："+'</td><td>'+"[" + lon.toFixed(2) + ", " + lat.toFixed(2) + " "+"]" +'</td></tr><tr><td>' +"地址:"+ '</td><td>'+response.address +'</td></tr><tr><td>'+"距震中距离:"+'</td><td>'+nearDistance.toFixed(1)+"公里"+'</td></tr><tr><td>'+"海拔"+'</td><td>'+z.toFixed(2)+"米"+'</td></tr></table>';
                    }).catch((error) => {
                        // 如果承诺失败，没有发现结果，则显示一条通用消息
                        this.view.popup.content = "无此处信息";
                    });
                }

            });

        });
    })
}


export default ArcMap;